# -*- coding: utf-8 -*-

import copy
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

import logging
logger = logging.getLogger('bt_server')

from app.models import BtResource
from . import BaseSerializer, TargetsReadOnly


class BtResourceBaseSerializer(BaseSerializer):
    """
        资源(Base)
    """
    download_rates = serializers.ListField(child=serializers.IntegerField(), read_only=True)
    upload_rates = serializers.ListField(child=serializers.IntegerField(), read_only=True)

    download_rate = serializers.IntegerField(max_value=1024*1024*1024, write_only=True, required=False)
    upload_rate = serializers.IntegerField(max_value=1024*1024*1024, write_only=True, required=False)

    class Meta:
        model = BtResource
        fields = (
            'id', 'name', 'category',  'info_hash', 'torrent_file_name', 'state', 'info_hash', 'active_time', 'announcing_to_dht', 'announcing_to_lsd', 'announcing_to_trackers',
            'is_finished', 'is_loaded', 'is_seeding', 'progress', 'completed_time', 'total_download', 'total_upload', 'size',

            # 只写字段
            'download_rate', 'upload_rate',

            # 只读字段
            'download_rates', 'upload_rates',
        )

    def is_valid(self, raise_exception=True):
        try:
            if not super(BtResourceBaseSerializer, self).is_valid(raise_exception):
                raise ValidationError(self.errors)
            logger.info('============== validated_data start =============')
            logger.info(self.validated_data)
            logger.info('============== validated_data end =============')
        except Exception as e:
            if raise_exception:
                raise
            return False
        return True

    def __codemsg_before_create_or_update(self, validated_data, *args):
        instance = None
        if args:
            instance = validated_data
            validated_data = args[0]
            target = TargetsReadOnly(instance, validated_data)
        else:
            target = TargetsReadOnly(validated_data)

        if validated_data.get('download_rate') is not None:
            # create case
            if not instance:
                validated_data['download_rates'] = [validated_data.pop('download_rate')]
            # update case
            else:
                validated_data['download_rates'] = copy.deepcopy(instance.download_rates)
                validated_data['download_rates'].append(validated_data.pop('download_rate'))
                if len(validated_data['download_rates']) >= 50:
                    validated_data['download_rates'] = validated_data['download_rates'][-50:]

        if validated_data.get('upload_rate') is not None:
            # create case
            if not instance:
                validated_data['upload_rates'] = [validated_data.pop('upload_rate')]
            # update case
            else:
                validated_data['upload_rates'] = copy.deepcopy(instance.upload_rates)
                validated_data['upload_rates'].append(validated_data.pop('upload_rate'))
                if len(validated_data['upload_rates']) >= 50:
                    validated_data['upload_rates'] = validated_data['upload_rates'][-50:]

    def create(self, validated_data):
        logger.info('++++++ create ++++++')
        self.__codemsg_before_create_or_update(validated_data)
        return super(BtResourceBaseSerializer, self).create(validated_data)

    def update(self, instance, validated_data):
        logger.info('++++++ update ++++++')
        self.__codemsg_before_create_or_update(instance, validated_data)
        return super(BtResourceBaseSerializer, self).update(instance, validated_data)


class BtResourceVerboseSerializer(BtResourceBaseSerializer):
    """
        资源(详细)
    """

    class Meta:
        model = BtResource
        fields = BtResourceBaseSerializer.Meta.fields + (
            # 只读字段
            'peers',
        )
